//
//  WBMainViewController.swift
//  新浪微博
//
//  Created by ZJ on 2017/10/10.
//  Copyright © 2017年 zj. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {

    //
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
        setupTimer()
        
        setupNewfeatureViews()
        
        delegate = self
        
        //
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        timer?.invalidate()
        
        NotificationCenter.default.removeObserver(self)
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    // MARK: - 监听方法
    @objc private func userLogin(n: Notification) {
        print("用户登录通知 \(n)")
        
        var when = DispatchTime.now()
        
        // 判断object
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录.")
            
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.clear)
            
            let nav = UINavigationController.init(rootViewController: WBOAuthViewController())
            
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    @objc private func composeStatus() {
        print("撰写微博")
        
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.gray
        let nav = UINavigationController.init(rootViewController: vc)
        
        present(nav, animated: true, completion: nil)
    }
    
    private lazy var composeButton: UIButton = UIButton()
}

extension WBMainViewController {
    private func setupNewfeatureViews() {
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        //1.检查版本
        //2.
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        
//        v.frame = view.bounds
        //3.添加视图
        view.addSubview(v)
    }
    
    private var isNewVersion: Bool {
//        print(Bundle.main.infoDictionary)
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print(currentVersion)
        
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("version")
        let sandboxVersion = (try? String.init(contentsOfFile: path)) ?? ""
        print(sandboxVersion)
        print(path)

        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        return currentVersion != sandboxVersion
    }
}

extension WBMainViewController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到 \(viewController)")
        
        // 1.
        let index = (childViewControllers as NSArray).index(of: viewController)
        if selectedIndex == 0 && index == selectedIndex {
            print("点击首页")
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData()
            })
            
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
}

extension WBMainViewController {
    private func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc private func updateTimer() {
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        WBNetworkManager.shared.unreadCount { (count) in
            print("检查到 \(count) 条新微博")
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            // ios 8.0
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

extension WBMainViewController {
    
    private func setupComposeButton() {
        composeButton.setImage(UIImage.init(named: "tabbar_compose_icon_add"), for: UIControlState.normal)
        composeButton.setBackgroundImage(UIImage.init(named: "tabbar_compose_button"), for: UIControlState.normal)
        composeButton.sizeToFit()
        
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        
        // 正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: UIControlEvents.touchUpInside)
    }
    
    private func setupChildControllers() {
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        //
        var data = NSData.init(contentsOfFile: jsonPath)
        if data == nil {
            // 从bundle加载配置 json
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData.init(contentsOfFile: path!)
        }
        
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as! [[String: AnyObject]] else {
            return
        }
        
//        let array = [
//            ["clsName": "WBHomeViewController", "title": "首页", "imageName": "home",
//             "visitorInfo": ["imageName": "", "message": "关注一些人，回这里看看有什么惊喜"]
//            ],
//            ["clsName": "WBMessageViewController", "title": "消息", "imageName": "message_center",
//             "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]
//            ],
//            ["clsName": "UIViewController"],
//            ["clsName": "WBDiscoverViewController", "title": "发现", "imageName": "discover",
//             "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]
//            ],
//            ["clsName": "WBProfileViewController", "title": "我", "imageName": "profile",
//             "visitorInfo": ["imageName": "visitordiscover_image_profile", "message": "登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]
//            ],
//            ]
//
//        // 测试数据格式是否正确 - 转换成 plist 数据更加直观
////        (array as NSArray).write(toFile: "/Users/zj/Desktop/demo.plist", atomically: true)
//        let data = try? JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData?)?.write(toFile: "/Users/zj/Desktop/demo.json", atomically: true)
        
        var arrayM = [UIViewController]()
        for dict in array {
            arrayM.append(controller(dict: dict))
        }
        
        viewControllers = arrayM
    }
    
    private func controller(dict: [String: AnyObject]) -> UIViewController {
        guard let clsName = dict["clsName"] as? String,
        let title = dict["title"] as? String ,
        let imageName = dict["imageName"] as? String,
        let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String: String] else {
            return UIViewController()
        }
        
        let vc = cls.init()
        
        vc.title = title
        // 设置
        vc.visitorInfoDictionary = visitorDict
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.orange], for: .highlighted)
        // 系统默认12号字，要设置Normal的字体大小
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue: 0))
        
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    }
}
